import { VrOrder } from './app/admin/ml/order';
import { X, ObservingObject } from 'x-orm';
import fetch from 'node-fetch';
import { strtotime, time, date } from 'locutus/php/datetime';
import { JSDOM } from 'jsdom';
import * as jquery from "jquery";
import * as jsdom from "jsdom";
import { ProxyMargin } from './app/admin/ml/proxy_margin';
import { returnFloat } from './lib/utils';
import { ProxyUser } from './app/admin/ml/proxy_user';
import { ORMCONFIG } from './config';

@X.Entity({
    primary: "id"
})
export class caipiao {
    id: string;
    cnumber: string;
    open_time: string;
    type: string;
}
export enum COrderStatus {
    ohno = 0,
    notopen = 10,
    lose = 20,
    win = 30,
    gotten = 40,
    saled = 50
}

export class Collect {

    async caipiao(start_time) {
        let url = 'http://kaijiang.500.com/static/public/ssc/xml/qihaoxml/date.xml';

        //查找数据库中最后一次采集的日期
        const lastOne = await X.of(caipiao).findOne({
            where: {
                type: "cqssc"
            },
            order: {
                open_time: 'desc',
            }
        });
        let lastTime;

        if (!lastOne) {
            lastTime = strtotime(start_time);
        }
        else {
            lastTime = strtotime(lastOne.open_time);
        }


        const now = time();
        while (true) {
            try {
                const day = date("Ymd", lastTime);
                const res = await fetch(url.replace('date', day));
                if (res.status == 404) {
                    break;
                }
                const text = await res.text();
                let dom = new JSDOM(text);
                const $: any = jquery(dom.window);
                $('row').each(function () {
                    let row = $(this);
                    const id = row.attr('expect');
                    const cnumber = row.attr('opencode');
                    const open_time = row.attr('opentime');
                    // let type = 'cqssc';
                    X.query(`
                insert into nw_caipiao 
                    (id,cnumber,open_time,add_time,type)
                values('${id}','${cnumber}','${open_time}','${now}','cqssc')`).catch(e => {
                            // console.log(e)
                        });
                });

                lastTime += 24 * 3600;

            }
            catch (e) {
                console.log("break")
                break;
            }

        }
    }

    async kaijiang() {
        console.log("正在开奖中");
        //开奖函数
        //当前期号
        const lastItem = await X.of(caipiao).findOne({
            where: {
                type: "cqssc",
            },
            order: {
                id: "desc"
            }
        });
        if (!lastItem) {
            return;
        }

        //查找所有小于当前期号的订单
        let orders = await X.of(VrOrder).find({
            where: {
                caipiao_status: COrderStatus.notopen,

                order_state : 20,
                caipiao_type: 'cqssc',
                term: {
                    let: lastItem.id
                }
            }
        });
        let cache: {
            [key: string]: caipiao
        } = {};
        for(let order of orders){
        // await Promise.all(orders.map(async order => {
            //如果还没付款，作废掉
            // if (order.order_state == 10) {
            //     order.order_state = 0;
            //     order.caipiao_status = COrderStatus.ohno;
            //     await X.save(order);
            //     continue;
            // }

            //已经付款的情况，开奖
            if (!order.term) {
                continue;
            }
            let target = cache[order.term] || (cache[order.term] = await X.of(caipiao).findOne({
                where: {
                    id: order.term
                }
            }))
            if (!target || !target.cnumber) {
                return;
            }
            let num = target.cnumber.split(",").pop();
            if (num === undefined) {
                return;
            }
            let guess = Number(num) % 2 == 0 ? 'double' : "single";
            //中奖
            if (guess == order.guess) {
                order.caipiao_status = COrderStatus.win;
            }
            else {
                order.caipiao_status = COrderStatus.lose;
            }
            await X.save(order);
        }
    }

    /**
     * 自动计算提成
     */
    async ticheng() {
        let orders = await X.of(VrOrder).find({
            where: {
                order_state: {
                    get: 20
                },
                is_cal: 0
            },
            addon: {
                proxy_parent: 1
            }
        });
        if (!orders.length) {
            return;
        }
        for(let order of orders){
            if(!order.from_proxy){
                continue;
            }
            if (await X.of(ProxyMargin).count({
                where: {
                    order_id: order.order_id
                }
            })) {
                continue;
            }
            let proxy = order.proxy_parent;
            if (!proxy) {
                continue;
            }
            if (proxy.id == 1) {
                continue;
            } 

            let item = proxy;
            let arr = [];
            try {
                while (true) {
                    arr.push(item);
                    await X.makeAddon(item, 'parent');
                    if (item.id == 1 || !item || !item.parent || item.parent.id == 1) {
                        break;
                    }
                    item = item.parent;
                }
            }
            catch (e) {
                arr = [];
            }

            arr = arr.reverse();
            if (!arr.length || arr[0].type != 'normal') {
                continue;
            }


            let goods_amount = (order.order_amount - order.s_fee - order.f_fee);
            let fee = order.s_fee;
            const moneys = [];
            // console.log(goods_amount)
            //预分配
            for (let i = 0; i < arr.length; i++) {
                //只有综合会员和经纪会员有货款分摊比例
                if (i == 0 || i == 1) {
                    goods_amount = returnFloat(goods_amount * arr[i].fentan / 100)
                    fee = returnFloat(fee * arr[i].shouxufei / 100);
                    moneys.push([arr[i].id, Number(goods_amount) + Number(fee)]);
                }
                else {
                    fee = returnFloat(fee * arr[i].shouxufei / 100);
                    moneys.push([arr[i].id, Number(fee)]);
                    // moneys[arr[i].id] = fee;
                }
                //减掉前一个的
                if (i > 0) {
                    moneys[i - 1][1] -= moneys[i][1];
                }
            }

            try {
                await X.transition(async x => {
                    for (const [id, money] of moneys) {
                        let info = await x.of(ProxyUser).findOne(id);
                        info.money += money;
                        await x.save(info);
                        // await X.query(`update nw_proxy_user set money = money + ${moneys[id]} where id = ${id}`);
                    }
                    let margin = new ProxyMargin;
                    margin.order_id = order.order_id;
                    margin.phone = order.buyer_phone;
                    let count = 0;
                    let types = ['normal', 'jingji', 'jigou', 'jujian'];
                    for (let i = 0; i < 4; i++) {
                        if (moneys[i]) {
                            margin[types[i] + '_id'] = moneys[i][0];
                            margin[types[i] + '_money'] = moneys[i][1];
                        }
                        else {
                            margin[types[i] + '_id'] = 0;
                            margin[types[i] + '_money'] = 0;
                        }
                    }
                    margin.add_time = time();
                    await x.save(margin);

                    //保存更改
                    order.is_cal = 1;
                    // await x.of(VrOrder).update(order.order_id,{
                    //     order_id : order.order_id,
                    //     is_cal : 1
                    // });
                    // console.log(ObservingObject.getChanged(order));

                    // console.log()
                    await x.save(order);
                })

            } catch (e) {
                console.log(e)
            }
 
        }
 
        console.log("ok")
    }

    async collect(start_time) {


        const loop = async () => {
            await this.caipiao(start_time);

            await this.kaijiang();

            console.log("计算提成中");
            await this.ticheng();

            



            setTimeout(loop, 30000);

            console.log("等待30秒重试");
        };
        loop();

        console.log("循环采集中");
    }
}

// export function startCollect(){
    X.startORM(ORMCONFIG).then(() => {
        let c = new Collect;
        c.collect("2017-09-28");
    });
// }
